#include <stdio.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <assert.h>
#include <unistd.h>
#include <stdlib.h>
#include <errno.h>
#include <sys/types.h>
#include <string.h>
#include <fcntl.h>
#include <aio.h>

#define BUFFER_SIZE 1024

int MAX_LIST = 2;

int main(int argc, char **argv) {
    //aio操作所需结构体
    struct aiocb rd;
    int serverfd, ret, couter;

    struct sockaddr_in address;
    bzero(&address, sizeof(address));
    address.sin_family = AF_INET;
    inet_pton(PF_INET, "127.0.0.1", &address.sin_addr);
    address.sin_port = htons(8000);

    serverfd = socket(AF_INET, SOCK_STREAM, 0);
    ret = bind(serverfd, (struct sockaddr*)&address, sizeof(address));

    listen(serverfd, 5);

    // struct sockaddr_in client_address;
    // socklen_t client_addrlength = sizeof(client_address);
    // int connfd = accept(serverfd, (struct sockaddr*)&client_address, &client_addrlength);

    bzero(&rd, sizeof(rd));
    rd.aio_buf = malloc(BUFFER_SIZE + 1);
    rd.aio_fildes = serverfd;
    rd.aio_nbytes = BUFFER_SIZE;
    rd.aio_offset = 0;

    //异步读
    ret = aio_read(&rd);
    if (ret < 0) {
        perror("aio_read");
        exit(1);
    }

    couter = 0;
    while(aio_error(&rd) == EINPROGRESS) {
        printf("第%d次\n", ++couter);
        sleep(1);
    }

    ret = aio_return(&rd);
    printf("\n\n返回值为:%d %ld %s\n", ret, rd.aio_offset, (char*)rd.aio_buf);

    return 0;


    // bzero(&rd, sizeof(rd));
    // rd.aio_buf = malloc(BUFFER_SIZE + 1);

    // rd.aio_fildes = connfd;
    // rd.aio_nbytes = BUFFER_SIZE;
    // rd.aio_offset = 0;

    // //异步读
    // ret = aio_read(&rd);
    // if (ret < 0) {
    //     perror("aio_read");
    //     exit(1);
    // }

    // couter = 0;
    // while(aio_error(&rd) == EINPROGRESS) {
    //     printf("第%d次\n", ++couter);
    //     sleep(1);
    // }

    // ret = aio_return(&rd);
    // printf("\n\n返回值为:%d %ld %s\n", ret, rd.aio_offset, (char*)rd.aio_buf);
    // return 0;
}